package com.qining618.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.qining618.cms.ucenter.service.TokenService;
import com.qining618.common.annotation.Access;
import com.qining618.common.contants.HeaderConstants;
import com.qining618.common.context.ContextHandle;
import com.qining618.common.model.AuthUser;
import com.qining618.common.model.TokenInfo;
import com.qining618.common.result.ApiResult;
import com.qining618.common.result.ErrorCode;
import com.qining618.common.utils.StringUtils;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author flt
 * @date 2019-08-16
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("AuthenticationInterceptor.preHandle");
        String tokenStr = request.getHeader(HeaderConstants.AUTHORIZATION);
        if (StringUtils.isNotBlank(tokenStr) && tokenStr.startsWith("Bearer ")) {
            tokenStr = tokenStr.replace("Bearer ", "");
        }

        if (StringUtils.isBlank(tokenStr)) {
            tokenStr = request.getParameter("token");
        }

        TokenInfo tokenInfo = null;
        AuthUser authUser = null;
        if (StringUtils.isNotBlank(tokenStr)) {
            tokenInfo = this.tokenService.findByAccessToken(tokenStr);
            if (tokenInfo != null) {
                authUser = tokenInfo.getAuthUser();
            }
        }

        // 请求信息放入线程中
        ContextHandle.add(request);
        ContextHandle.add(authUser);

        if (!(handler instanceof HandlerMethod)) {
            log.warn("当前操作handler不为HandlerMethod=" + handler.getClass().getName() + ",req=" + request.getQueryString());
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String methodName = handlerMethod.getMethod().getName();

        Access access = handlerMethod.getMethod().getAnnotation(Access.class);
        if (access == null) {
            log.info("当前访问methodName=" + methodName + "不需要登陆");
            return true;
        }

        if (authUser == null) {
            // 未授权
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            @Cleanup PrintWriter printWriter = response.getWriter();
            printWriter.write(JSON.toJSONString(ApiResult.failed(ErrorCode.UNAUTHORIZED)));
            return false;
        }

        if (tokenInfo.getExpireTime().getTime() < System.currentTimeMillis()) {
            log.info("当前访问methodName=" + methodName + "凭证已过期");
            // 未授权
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            @Cleanup PrintWriter printWriter = response.getWriter();
            printWriter.write(JSON.toJSONString(ApiResult.failed(ErrorCode.UNAUTHORIZED)));
            return false;
        }

        if (access.needAdmin() && !authUser.getIsAdmin()) {
            log.info("当前访问methodName=" + methodName + "授权用户无权访问");
            // 没有权限
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            @Cleanup PrintWriter printWriter = response.getWriter();
            printWriter.write(JSON.toJSONString(ApiResult.failed(ErrorCode.FORBIDDEN)));
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("AuthenticationInterceptor.afterCompletion");
        ContextHandle.clean();
    }
}
